<template>
  <div>
    <div class="page-title"></div>
    <div class="page-content">
      <el-form :inline="true" v-model="filterQuery">
        <el-form-item label="公司名称：">
          <select-tree
            placeholder="公司名称"
            v-model="filterQuery.nm"
            :treeProps="treeProps"
            style="width:280px;margin-left:10px"
            clearable
            filterable
            @change="companyChange"
          >
          </select-tree>
        </el-form-item>
        <el-form-item label="姓名：">
          <el-input
            v-model="filterQuery.name"
            placeholder="请输入姓名"
            style="width:200px"
            clearable
          >
          </el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleQuery"
            >查询</el-button
          >
          <el-button type="primary" @click="createUserVisible = true"
            >创建用户</el-button
          >
        </el-form-item>
      </el-form>

      <el-table
        :data="tableData"
        v-loading="loading"
        border
        style="width: 100%"
      >
        <el-table-column
          type="index"
          width="50"
          header-align="center"
          label="序号"
          :index="this.indexStartNum"
          align="center"
        ></el-table-column>
        <el-table-column
          label="公司名称"
          prop="companyname"
          header-align="center"
          width="200px"
        >
        </el-table-column>
        <el-table-column
          label="部门名称"
          prop="departmentname"
          header-align="center"
          width="200px"
        >
        </el-table-column>
        <el-table-column label="姓名" prop="name" header-align="center">
        </el-table-column>
        <el-table-column
          label="用户名"
          prop="username"
          header-align="center"
          width="150px"
        >
        </el-table-column>
        <el-table-column
          label="性别"
          prop="sex"
          header-align="center"
          width="100px"
        >
        </el-table-column>
        <el-table-column
          label="民族"
          prop="nation"
          header-align="center"
          width="120"
        >
        </el-table-column>
        <!-- <el-table-column
          label="身份证号"
          prop="idno"
          header-align="center"
          width="160"
        >
        </el-table-column> -->
        <el-table-column
          label="电话"
          prop="mobilephone"
          align="center"
          header-align="center"
          width="230%"
        ></el-table-column>
        <el-table-column
          label="操作"
          align="center"
          header-align="center"
          width="300%"
        >
          <template slot-scope="scope">
            <div class="inline-td">
              <el-button
                size="mini"
                type="primary"
                @click="handleRegister(scope.row)"
                v-if="scope.row.username == null"
                >注册</el-button
              >
              <el-button
                v-else
                size="mini"
                type="danger"
                @click="handleSubmitReturn(scope.row)"
                >注销</el-button
              >
              <el-button
                size="mini"
                type="primary"
                icon="el-icon-edit"
                @click="handleEdit(scope.row.code)"
                >编辑</el-button
              >
              <el-button
                size="mini"
                type="danger"
                icon="el-icon-delete"
                @click="handleDeleteUser(scope.row.code)"
                >删除</el-button
              >
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-dialog title="注册" :visible.sync="dialogFormVisible" width="600px">
        <el-form :model="form" label-width="auto" :rules="rules" ref="form">
          <el-form-item label="公司名称">
            <el-input
              v-model="form.companyname"
              autocomplete="off"
              disabled
            ></el-input>
          </el-form-item>
          <el-form-item label="部门名称">
            <el-input
              v-model="form.departmentname"
              autocomplete="off"
              disabled
            ></el-input>
          </el-form-item>
          <el-form-item label="姓名">
            <el-input
              v-model="form.name"
              autocomplete="off"
              disabled
            ></el-input>
          </el-form-item>
          <el-form-item label="角色" prop="sysrole">
            <el-select
              v-model="form.sysrole"
              placeholder="请选择角色"
              clearable
              filterable
            >
              <el-option
                v-for="item in options"
                :key="item"
                :label="item"
                :value="item"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="用户名" prop="username">
            <el-input v-model="form.username" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input
              v-model="form.password"
              autocomplete="off"
              type="password"
            ></el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="checkPass">
            <el-input
              v-model="form.checkPass"
              autocomplete="off"
              type="password"
            ></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="registerSucceedUser('form')"
            >确 定</el-button
          >
        </div>
      </el-dialog>
      <el-dialog
        title="创建用户"
        :visible.sync="createUserVisible"
        width="600px"
      >
        <el-form :model="users" label-width="auto" :rules="rules" ref="users">
          <el-form-item label="部门名称" prop="nm">
            <select-tree
              placeholder="部门名称"
              v-model="users.nm"
              :treeProps="treeUser"
              clearable
              filterable
              @change="userDepartmentChange"
              style="width:80%"
            >
            </select-tree>
          </el-form-item>
          <el-form-item label="姓名" prop="name">
            <el-input
              v-model="users.name"
              autocomplete="off"
              style="width:80%"
            ></el-input>
          </el-form-item>

          <el-form-item label="性别" prop="sex">
            <el-select
              v-model="users.sex"
              placeholder="请选择性别"
              style="width:80%"
              clearable=""
            >
              <el-option label="男" value="男"></el-option>
              <el-option label="女" value="女"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="民族" prop="nation">
            <el-input
              v-model="users.nation"
              autocomplete="off"
              style="width:80%"
              label="汉族"
              clearable=""
            ></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="telephonenumber">
            <el-input
              v-model="users.telephonenumber"
              autocomplete="off"
              style="width:80%"
            ></el-input>
          </el-form-item>
          <el-form-item label="员工编号" prop="code">
            <el-input
              v-model="users.code"
              autocomplete="off"
              style="width:80%"
            ></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="createUserVisible = false">取 消</el-button>
          <el-button type="primary" @click="cresteSucceedUser('users')"
            >确 定</el-button
          >
        </div>
      </el-dialog>
      <el-dialog title="编辑用户" :visible.sync="editUserVisible" width="600px">
        <el-form :model="edits" label-width="auto" :rules="rules" ref="edits">
          <el-form-item label="部门名称" prop="nm">
            <select-tree
              placeholder="部门名称"
              v-model="edits.nm"
              :treeProps="treeUser"
              clearable
              filterable
              @change="editUserDepartmentChange"
              style="width:80%"
            >
            </select-tree>
          </el-form-item>
          <el-form-item label="姓名" prop="name">
            <el-input
              v-model="edits.name"
              autocomplete="off"
              style="width:80%"
            ></el-input>
          </el-form-item>

          <el-form-item label="性别" prop="sex">
            <el-select
              v-model="edits.sex"
              placeholder="请选择性别"
              style="width:80%"
              clearable=""
            >
              <el-option label="男" value="男"></el-option>
              <el-option label="女" value="女"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="民族" prop="nation">
            <el-input
              v-model="edits.nation"
              autocomplete="off"
              style="width:80%"
              label="汉族"
              clearable=""
            ></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="telephonenumber">
            <el-input
              v-model="edits.telephonenumber"
              autocomplete="off"
              style="width:80%"
            ></el-input>
          </el-form-item>
          <el-form-item label="员工编号" prop="code">
            <el-input
              v-model="edits.code"
              autocomplete="off"
              style="width:80%"
            ></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="editUserVisible = false">取 消</el-button>
          <el-button type="primary" @click="editSucceedUser('edits')"
            >确 定</el-button
          >
        </div>
      </el-dialog>
      <el-dialog title="提示" :visible.sync="dialogVisible" width="30%">
        <span>此操作将永久删除该条记录, 是否继续?</span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitDelet">确 定</el-button>
        </span>
      </el-dialog>
      <div class="pagination-base">
        <el-pagination
          @current-change="handlePageChange"
          :current-page="filterQuery.pageIdx"
          :page-size="filterQuery.pageSize"
          :total="filterQuery.total"
          background
          layout="total, prev, pager, next, jumper"
          style="float:right;"
        >
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import {
  GetCompanyTree,
  GetQueryData,
  RegisterUser,
  GetLogout,
  GetRoles,
  CreateUser,
  EditUser,
  UpdateEdit,
  deleteUser
} from "@/api/module/userManagement";
// import '@riophae/vue-treeselect/dist/vue-treeselect.css'
// import Treeselect from "@riophae/vue-treeselect";
import SelectTree from "./SelectTree";
export default {
  computed: {
    currentUser() {
      return GetCurrentUser();
    }
  },
  components: { SelectTree },
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        if (this.form.checkPass !== "") {
          this.$refs.form.validateField("checkPass");
        }
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.form.password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" }
        ],
        sysrole: [{ required: true, message: "请选择角色", trigger: "change" }],
        password: [
          { required: true, validator: validatePass, trigger: "blur" }
        ],
        checkPass: [
          { required: true, validator: validatePass2, trigger: "blur" }
        ],
        name: [{ required: true, message: "请输入名字", trigger: "blur" }],
        sex: [{ required: true, message: "请选择性别", trigger: "change" }],
        nation: [{ required: true, message: "请输入民族", trigger: "blur" }],
        code: [{ required: true, message: "请输入员工编号", trigger: "blur" }],
        nm: [
          {
            required: true,
            message: "请选择部门名称",
            trigger: ["blur", "change"]
          }
        ]
      },
      dialogVisible: false,
      dialogFormVisible: false,
      createUserVisible: false,
      editUserVisible: false,
      form: {
        companyname: "",
        departmentname: "",
        name: "",
        username: "",
        password: "",
        checkPass: "",
        sysrole: ""
      },
      users: {
        companyName: "",
        departmentName: "",
        name: "",
        sex: "",
        nation: "汉族",
        telephonenumber: "",
        code: "",
        groupCode: "",
        nm: ""
      },
      edits: {
        companyName: "",
        departmentName: "",
        name: "",
        sex: "",
        nation: "汉族",
        telephonenumber: "",
        code: "",
        groupCode: "",
        nm: ""
      },
      indexStartNum: 1,
      tableData: [],
      departmentData: [],
      formData: {
        regName: ""
      },
      types: [],
      companyData: [],
      options: [],
      treeProps: {
        data: [],
        props: {
          label: "name",
          disabled(data) {
            console.log(data, 33);
            return data.level % 2;
          }
        }
      },
      treeUser: {
        data: [],
        props: {
          label: "name",
          disabled(data) {
            return data.level !== 4;
          }
        }
      },
      normalizer(node) {
        return {
          label: node.name
        };
      },
      // DeleteUser: "",
      filterQuery: {
        nm: "",
        total: 0,
        companyname: "",
        departmentname: "",
        name: "",
        pageIdx: 1,
        pageSize: 10
      },
      DeleteUserCode: "",
      DefaultQuery: "",
      inputRegName: "",
      inputTypeName: "",
      loading: false,
      dateRange: "", //时间查询，v-model绑定
      regNameAyy: [],
      regNameListAyy: [],
      fileList: []
    };
  },

  mounted() {
    this.getCompanyTree();
    this.handleQuery();
    this.loadFilterParams();
    this.getRoleData();
    this.getUserTree();
  },

  methods: {
    // 删除数据
    handleDeleteUser(code) {
      this.DeleteUserCode = code;
      this.dialogVisible = true;
      this.handleQuery();
    },
    // 网络请求删除数据
    DeleteUser() {
      deleteUser(this.DeleteUserCode)
        .then(res => {
          // this.$message({
          //   // // message: "恭喜你，删除成功",
          //   // type: "success"
          // });
          this.handleQuery(this.filterQuery);
          console.log(res);
        })
        .catch(e => {
          console.log(e);
          this.$message.error("删除失败");
        });
    },
    // 二次确认删除数据
    submitDelet() {
      this.dialogVisible = false;
      this.DeleteUser();
    },
    // 提交更新
    editSucceedUser() {
      this.editUpdateUser("edits");
    },
    // 编辑用户提交
    editUpdateUser(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          UpdateEdit(this.edits).then(
            () => {
              this.editUserVisible = false;
              this.handleQuery();
              //this.$message.success("操作成功");
              //this.$router.go(-1); //返回上一url
            },
            err => {
              this.$message.error(err.message);
            }
          );
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 获取角色
    getRoleData() {
      // let params = {
      //   label: '角色'
      // }
      GetRoles()
        .then(res => {
          console.log("ss", res);
          this.options = res.data.data;
        })

        .catch(() => {});
    },
    // 注销
    handleSubmitReturn(item) {
      this.$confirm("此操作将永久注销此账号, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          GetLogout({ code: item.code }).then(
            () => {
              this.handleQuery();
            },
            err => {
              this.$message.error(err.message);
            }
          );
        })
        .catch(() => {});
    },
    // 编辑用户
    handleEdit(code) {
      this.getUsersEdit(code);
      this.editUserVisible = true;
    },
    // 点击编辑获取用户详情
    getUsersEdit(code) {
      EditUser(code)
        .then(res => {
          console.log(res, 678);
          const data = res.data.data;
          this.edits = { ...data, nm: data.groupCode };
          this.editUserVisible = true;
        })
        .catch(err => {
          this.$message.error(err.message);
        });
    },
    handleRegister(row) {
      const { companyname, departmentname, name, code } = row;
      this.form = { ...this.form, companyname, departmentname, name, code };
      this.dialogFormVisible = true;
    },
    setLevel(arr = [], level = 1) {
      return arr.map(item => {
        item.children && item.children.length
          ? (item.children = this.setLevel(item.children, level + 1))
          : delete item.children;
        return {
          ...item,
          level,
          // disabled: !!(level % 2),
          companyname: level === 2 ? item.name : "",
          departmentname: level === 4 ? item.name : ""
        };
      });
    },
    // 创建用户
    cresteSucceedUser(userName) {
      console.log("u", this.$refs);
      this.$refs[userName].validate(valid => {
        console.log("f", valid);
        if (valid) {
          console.log(this.users, 13);
          const {
            companyName,
            departmentName,
            name,
            sex,
            nation,
            mobilePhone,
            code,
            groupCode
          } = this.users;
          CreateUser({
            companyName,
            departmentName,
            name,
            sex,
            nation,
            mobilePhone,
            code,
            groupCode
          })
            .then(() => {
              this.createUserVisible = false; //返回上一url
              this.$refs[userName].resetFields();
              this.handleQuery();
            })
            .catch(err => {
              console.log("err", err);
              this.$message.error(err.message);
            });
        } else {
          this.$notify.warning({
            title: "温馨提示",
            message: "请检查必填项"
          });
          return false;
        }
      });
    },
    // 注册
    registerSucceedUser(formName) {
      console.log("------", this.$refs);
      this.$refs[formName].validate(valid => {
        console.log("for", valid);
        if (valid) {
          console.log(this.form, 33);
          const {
            companyname,
            username,
            password,
            name,
            code,
            sysrole
          } = this.form;
          RegisterUser({ companyname, username, password, name, code, sysrole })
            .then(() => {
              this.dialogFormVisible = false; //返回上一url
              this.$refs[formName].resetFields();
              this.handleQuery();
            })
            .catch(err => {
              console.log("err", err);
              this.$message.error(err.message);
            });
        } else {
          this.$notify.warning({
            title: "温馨提示",
            message: "请检查必填项"
          });
          return false;
        }
      });
    },
    // 编辑用户部门变化
    editUserDepartmentChange(data, node) {
      const { id, departmentname } = node;
      this.edits.groupCode = id;
      this.edits.departmentName = departmentname;
      this.$refs.edits.validateField("nm");
    },
    // 用户部门变化
    userDepartmentChange(data, node) {
      const { id, departmentname } = node;
      this.users.groupCode = id;
      this.users.departmentName = departmentname;
      this.$refs.users.validateField("nm");
    },
    // 公司部门变化
    companyChange(data, obj) {
      const { companyname, departmentname } = obj;
      this.filterQuery.companyname = companyname;
      this.filterQuery.departmentname = departmentname;
    },
    // 查询
    handleQuery() {
      console.log(this.filterQuery, 33);
      let filterQuery = {
        name: this.filterQuery.name,
        companyname: this.filterQuery.companyname,
        departmentname: this.filterQuery.departmentname,
        num: this.filterQuery.pageIdx - 1,
        size: this.filterQuery.pageSize
      };
      GetQueryData(filterQuery).then(res => {
        console.log("rr", this.filterQuery.name);
        this.indexStartNum =
          (this.filterQuery.pageIdx - 1) * this.filterQuery.pageSize + 1;
        this.tableData = res.data.data.content;
        this.filterQuery.total = res.data.data.totalElements;
      });
    },
    // 公司名称树状
    getCompanyTree() {
      GetCompanyTree()
        .then(res => {
          this.treeProps.data = this.setLevel([res.data.data]);
          console.log(
            "getCompanyTree -> this.treeProps.data",
            this.treeProps.data
          );
        })
        .catch(err => {
          console.log(err);
          this.$message.error(err.message);
        });
    },
    // 创建用户树状
    getUserTree() {
      GetCompanyTree()
        .then(res => {
          this.treeUser.data = this.setLevel([res.data.data]);
          console.log(
            "getCompanyTree -> this.treeUser.data",
            this.treeUser.data
          );
        })
        .catch(err => {
          console.log(err);
          this.$message.error(err.message);
        });
    },
    //加载默认条件
    loadFilterParams() {},
    checkFilterParams() {
      //datepicker range 绑定的数据是数组,需要拆成后端识别的2个参数
      if (this.dateRange && this.dateRange.length === 2) {
        this.filterQuery.beginDate1 = this.dateRange[0];
        this.filterQuery.beginDate2 = this.dateRange[1];
      } else {
        this.filterQuery.beginDate1 = "";
        this.filterQuery.beginDate2 = "";
      }
    },
    //页码改变
    handlePageChange(page) {
      this.filterQuery.pageIdx = page;
      this.handleQuery();
    },

    //查询文件名称下拉框
    querySearch(queryString, cb) {
      let results = queryString
        ? this.regNameListAyy.filter(this.createStateFilter(queryString))
        : this.regNameListAyy;
      clearTimeout(this.timeout);
      this.timeout = setTimeout(() => {
        cb(results);
      }, 1000 * Math.random());
    },
    createStateFilter(queryString) {
      return inputRegName => {
        return (
          inputRegName.value
            .toLowerCase()
            .indexOf(queryString.toLowerCase()) !== -1
        );
      };
    },
    onChangedSearchType(selectValue) {
      if (selectValue != "") {
        let obj = {};
        //遍历下拉数组中的item
        obj = this.types.find(item => {
          return item.name === selectValue;
        });
        this.filterQuery.typeCode = obj.dictCode;
      } else {
        this.filterQuery.typeCode = "";
      }
    },

    onChangedType(selectValue) {
      let obj = {};
      //遍历下拉数组中的item
      obj = this.types.find(item => {
        return item.name === selectValue;
      });
      this.formData.typeName = obj.name;
      this.formData.typeCode = obj.dictCode;
    }
  }
};
</script>

<style>
.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
</style>
